package P150;

public class P54 {

    private static class ListNode {
        int      val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int k = 0;
        ListNode head = null;
        ListNode next = head;
        do {
            int int1 = l1 == null ? 0 : l1.val;
            int int2 = l2 == null ? 0 : l2.val;
            int sum = int2 + int1 + k;
            if (sum >= 10) {
                k = 1;
                sum -= 10;
            } else {
                k = 0;
            }
            if (head == null) {
                head = new ListNode(sum);
                next = head;
            } else {
                next.next = new ListNode(sum);
                next = next.next;
            }
            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;
        } while (l1 != null || l2 != null);
        if (k!=0) {
            next.next = new ListNode(k);
        }
        return head;
    }


    public static void main(String[] args) {
        ListNode head1 = new ListNode(2, new ListNode(4, new ListNode(3)));
        ListNode head2 = new ListNode(5, new ListNode(6, new ListNode(4)));
        ListNode listNode = addTwoNumbers(head1, head2);
        while (listNode != null) {
            System.out.print(listNode.val);
            listNode = listNode.next;
        }
    }
}
